<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="借款客户"
          @keyup.enter.native="getData()"
          @clear="getData()"
          clearable
          v-model="params.customer_name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="导入时间(开始)"
          end-placeholder="导入时间(截止)"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- @selection-change="handleSelectionChange"
          row-key="customer_related_id" -->
    <c-table
      v-loading="loading"
      border
      class="table-sm"
      ref="multipleTable"
      name="table"
      :columns="tableColumns"
      :data="tableData"
      @row-click="selectRow"
    >
      <template v-slot:select="scope">
        <el-radio
          @click.stop
          v-model="selectId"
          :label="scope.row.customer_related_id"
          @change="selectRowData(scope.row)"
        >
          &nbsp;
        </el-radio>
      </template>
    </c-table>

    <div class="query-pagination">
      <div class="pl-3">
        <!-- <el-checkbox
          v-model="allChecked"
          label="全选所有页"
          :disabled="loading"
          @change="handleSelectAll"
        ></el-checkbox>
        <small class="text-muted">
          (已选择
          <span class="text-info">{{ selectLen }}</span>
          个项目)
        </small> -->
      </div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <div class="text-center mt-3">
      <el-button type="primary" class="btn-long" @click="handleConfirm">推荐</el-button>
      <el-button class="btn-long" @click="handleDismiss">取消</el-button>
    </div>

    <el-dialog
      title="项目推荐"
      :visible.sync="confirmVisible"
      :close-on-click-modal="false"
      append-to-body
      width="500px"
    >
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">担保公司：</div>
        <div class="col-8">
          <div class="pr-5">
            <select-credit-org
              class="w-100"
              v-model="selectedCreditOrgId"
              @change="handleSelectCreditOrg"
            ></select-credit-org>
          </div>
        </div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">推荐数量：</div>
        <div class="col-8">{{ selectLen }} 个</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">授信总额：</div>
        <div class="col-8">{{ totalFunds }} 万元</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">支用总额：</div>
        <div class="col-8">{{ totalUseFunds }} 万元</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">总担保费：</div>
        <div class="col-8">{{ totalGuaFee }} 元</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">推荐日期：</div>
        <div class="col-8">{{ submitTime }}</div>
      </div>
      <div class="row mb-2">
        <div class="col-4 text-right text-muted">附件（推荐函）：</div>
        <div class="col-8">
          <upload-oss
            multiple
            ref="attachUpload"
            :dir="dir"
            :file-name="0"
            :file-list="attachList"
            :on-complete="handleAttachComplete"
          ></upload-oss>
        </div>
      </div>
      <div class="text-center mt-5">
        <el-button type="primary" class="btn-long" :loading="loading" @click="handleRecommend">
          确认推荐
        </el-button>
        <el-button class="btn-long" :disabled="loading" @click="confirmVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <attach-dialog :visible.sync="attachVisible" :project-data="attachProjectData"></attach-dialog>

    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="viewBatchNo"
      :tab-name="viewTabName"
      :query-id="viewQueryId"
    ></project-view-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { strip, dateFormat, arrayToString, tuid } from '@vimi/utils-tool'

import { lastPickerShortcuts } from '@/common/plugins/tools/date'
import { baseTableColumns, dataAdapter, fastParams } from '@/bank/views/fast/index'

import AttachDialog from '@/bank/views/fast/AttachDialog'
import ProjectViewDialog from '@/bank/views/fast/ProjectViewDialog'
import SelectCreditOrg from '@/bank/views/business/library/SelectCredit'

export default {
  components: {
    AttachDialog,
    ProjectViewDialog,
    SelectCreditOrg,
  },
  props: {
    visible: Boolean,
  },
  mixins: [fastParams],
  data() {
    return {
      batchKey: 'customer_related_quick_batch_id',

      loading: false,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'org_class.eq': '',
        'recommend_status.eq': 0,
        'channel_claim_status.eq': 1,
        'datum_status.eq': 1,
      },
      // pageParams: {
      //   index: 1,
      //   size: 10,
      // },
      order: {
        N1create_time: 'desc',
        N2update_time: 'desc',
      },
      tableName: 'customer_related_quick',
      tableCount: 0,
      // totalPages: 0,
      tableData: [],
      // allData: [],
      tableColumns: [
        // {
        //   attrs: {
        //     label: '选择',
        //     type: 'selection',
        //     align: 'center',
        //     width: 55,
        //     reserveSelection: true,
        //   },
        // },
        {
          attrs: {
            label: '选择',
            align: 'center',
          },
          slot: 'select',
        },
        ...baseTableColumns,
        { attrs: { label: '导入时间', prop: 'createTime', align: 'center', minWidth: '90px' } },
        {
          attrs: { label: '操作', align: 'center', minWidth: '180px' },
          operations: [
            { name: '上传', event: this.handleUpload },
            { name: '查看', event: this.handleView },
            { name: '附件', event: this.handleAttach },
          ],
        },
      ],

      // 选择担保机构
      selectedCreditOrgId: '',
      selectedCreditOrg: {},

      // 选择
      selectId: '',
      multipleSelection: [],
      // allChecked: false,

      // 导入时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },

      // 推荐
      confirmVisible: false,
      totalFunds: 0,
      submitTime: '',
      totalGuaFee: 0,
      totalGuaRate: 0,
      totalUseFunds: 0,

      // 附件上传
      attachVisible: false,
      attachProjectData: {},

      viewVisible: false,
      viewQueryId: '',
      viewTabName: 'detail',
      viewBatchNo: '',

      dir: '',
      attachList: [],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org']),
    selectLen() {
      return this.multipleSelection.length
    },
    // allLen() {
    //   return this.allData.length
    // },
  },
  watch: {
    visible: {
      handler: function (val) {
        if (val) {
          this.dir = `bank/rec/${tuid()}`
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    selectRow(row) {
      this.selectId = row.customer_related_id || ''
      this.multipleSelection = [{ ...row }]
    },
    selectRowData(row) {
      // 没有执行。。
      this.multipleSelection = [{ ...row }]
    },
    getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          { ...this.params, ...this.baseParams },
          this.order
        )
        .then(res => {
          this.tableData = (res?.data?.data ?? []).map(this.dataAdapter)
          this.tableCount = res?.data?.totalCount ?? 0
          // this.totalPages = Math.ceil(this.tableCount / this.pageParams.size)
          // this.getPageData(1)
        })
        .finally(() => {
          this.loading = false
        })
    },

    dataAdapter(item) {
      item = dataAdapter(item)
      return item
    },

    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['create_time.gte'] = start
        this.params['create_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['create_time.gte'] = ''
        this.params['create_time.lte'] = ''
      }
      this.getData()
    },

    // getPageData(index) {
    //   this.tableData = []
    //   this.pageParams.index = index
    //   const start = (index - 1) * this.pageParams.size
    //   const end = this.totalPages <= index ? this.allLen : start + this.pageParams.size
    //   for (let i = start; i < end; i++) {
    //     this.tableData.push(this.allData[i])
    //   }
    // },

    // handleSelectionChange(val) {
    //   this.multipleSelection = val
    //   this.allChecked = this.selectLen === this.allLen
    // },

    // // 全选
    // handleSelectAll(val) {
    //   const $tableRef = this.$refs.multipleTable.$refs.table
    //   if (!$tableRef) return

    //   if (val) {
    //     $tableRef.store.states.selection = this.allData.slice()
    //     $tableRef.$emit('selection-change', this.allData.slice())
    //     $tableRef.store.updateAllSelected()
    //   } else {
    //     $tableRef.clearSelection()
    //   }
    // },

    // clearSelect() {
    //   const $tableRef = this.$refs.multipleTable.$refs.table
    //   if (!$tableRef) return
    //   $tableRef.clearSelection()
    // },

    reset() {
      this.multipleSelection = []
      // this.allChecked = false
      // this.clearSelect()
    },

    handleUpload(row = {}) {
      this.attachProjectData = row
      this.attachVisible = true
    },

    handleView(row = {}) {
      this.viewQueryId = row.customer_related_id
      this.viewBatchNo = row[this.batchKey]
      this.viewTabName = 'detail'
      this.viewVisible = true
    },

    handleAttach(row = {}) {
      this.viewQueryId = row.customer_related_id
      this.viewBatchNo = row[this.batchKey]
      this.viewTabName = 'attach'
      this.viewVisible = true
    },

    handleSelectCreditOrg(value, org) {
      this.selectedCreditOrg = org
    },

    handleConfirm() {
      if (!this.selectLen) {
        return this.$message.error(this.tableData.length ? '请先选择推荐项目' : '暂无可推荐的项目')
      }

      // 项目总额
      let totalFunds = 0
      let totalGuaFee = 0
      let totalUseFunds = 0
      for (const project of this.multipleSelection) {
        totalFunds += +project.funds || 0
        totalUseFunds += +project.cur_use_funds || 0
        totalGuaFee += +project.gua_fee || 0
      }
      this.totalFunds = strip(totalFunds)
      this.totalGuaFee = strip(totalGuaFee)
      this.totalUseFunds = strip(totalUseFunds)
      // 担保费费取第一个 @唐超_20210430
      this.totalGuaRate = this.multipleSelection[0].gua_rate || 0

      // 推荐日期
      this.submitTime = dateFormat(new Date(), 'yyyy年MM月dd日')

      this.confirmVisible = true
    },

    handleRecommend() {
      if (!this.selectedCreditOrgId) {
        return this.$message.error('请选择担保公司')
      }
      this.$refs.attachUpload.submit()
    },

    handleAttachComplete(files) {
      const attachment = arrayToString(files.map(it => it.url))
      this.handleSubmit(attachment)
    },

    handleSubmit(attachment) {
      const {
        user: { userId, realName },
        org: { orgName },
        clientId,
        selectLen,
        totalFunds,
        totalGuaFee,
        totalGuaRate,
        totalUseFunds,
      } = this
      const masterTable = 'customer_related_quick_batch'
      const slaveTable = 'customer_related_quick_batch_detail'

      const masterData = {
        attachment,
        project_amount: selectLen,
        project_funds: totalFunds,
        gua_fee: totalGuaFee,
        gua_rate: totalGuaRate,
        cur_use_funds_total: totalUseFunds,
        bank_id: clientId,
        bank_name: orgName,
        service_id: this.selectedCreditOrgId,
        service_name: this.selectedCreditOrg.agency_name,
        submit_person: userId,
        submit_person_name: realName,
      }
      const slaveData = this.multipleSelection.map(it => ({
        customer_related_id: it.customer_related_id,
        submit_person: userId,
        submit_person_name: realName,
        update_person: userId,
      }))
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: masterTable,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: slaveTable,
      }

      // 关联添加
      this.loading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(res => {
          this.$message.success('推荐成功！')
          this.confirmVisible = false
          this.$emit('success', res)
          this.handleDismiss()
        })
        .catch(() => {
          this.$message.error('推荐失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleDismiss(e) {
      this.reset()
      this.$emit('dismiss', e)
    },
  },
}
</script>

<style lang="scss" scoped></style>
